<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header to="/buildHouse" :back="true" />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <subheadings :name="'房屋加固典型案例'" />
          <SecondClassicCase />
        </div>
        <div class="app-left-item">
          <subheadings :name="'近五年典型案例提交情况'" />
          <CaseSubmissionStatus />
        </div>
        <div class="app-left-item">
          <subheadings :name="'典型案例工程类别占比情况'" />
          <CategoryProportion />
        </div>
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="'全国房屋加固改造典型案例'" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '0px', left: '42px' }" />
          <!-- <IndexMap></IndexMap> -->
          <OlMap :refId="'’housereinforce'" style="height: 100%" @getMap="getMap"></OlMap>
          <div ref="popupElement" class="popup-bg" id="map-popup">
            <div class="triangle"></div>
            <div class="popup-head">
              <div class="popup-head-title">典型案例情况</div>
              <div style="cursor: pointer" class="popup-head-x" @click="hidePopup()">X</div>
            </div>
            <div class="popup-content">
              <div class="popup-table">
                <el-table max-height="150" :data="tableData">
                  <el-table-column prop="name" label="工程名称" :header-align="headerAlign">
                    <template #default="scope">
                      <div class="centered-cell">{{ scope.row.name }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="type" label="工程类型" :header-align="headerAlign">
                    <template #default="scope">
                      <div style="color: #fff" class="centered-cell">{{ scope.row.type }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="option" label="操作" :header-align="headerAlign">
                    <template #default="scope">
                      <div
                        style="color: #46ffff; cursor: pointer"
                        class="centered-cell"
                        @click="gotoCaseInfo(scope.row)"
                      >
                        {{ '查看详情' }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-right-item">
          <EvaluationStatistics :name="'评估统计'" @searchFn="searchFn" />
        </div>
        <div class="app-right-item">
          <subheadings :name="'提交典型案例数量（TOP5）'" />
          <CaseNumber />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
import { useRouter } from 'vue-router';
import SecondClassicCase from '../components/SecondClassicCase.vue';
import CaseSubmissionStatus from '../components/CaseSubmissionStatus.vue';
import CategoryProportion from '../components/CategoryProportion.vue';
import EvaluationStatistics from '../components/EvaluationStatistics.vue';
import CaseNumber from '../components/CaseNumber.vue';
import OlMap from '@/components/Olmap';
import { DoubleClickZoom, MouseWheelZoom, DragPan } from 'ol/interaction';
import { Style, Circle as CircleStyle, Fill, Stroke, Text, Icon } from 'ol/style';
import { Feature } from 'ol';
import { Point } from 'ol/geom';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import Overlay from 'ol/Overlay';
import { Select } from 'ol/interaction';
import point_house_img from '@/assets/map/image/newImage/redMarkerLarge.png';
import popup_img from '@/assets/map/image/newImage/popup-img.png';
import { getChinaBaseMap, getBaseDir } from '@/map/projMap.js';
import { getMapViewCase } from '@/api/buildHouse.js';

const mapInstance = ref(null);
const pointsLayer = ref(null);
const pointsData = ref(null);
const searchValue = ref({ type: 3, category: 1 });

const router = useRouter();

const mapPopupLayer = ref(null);
const popupElement = ref();
const headerAlign = 'center'; // 设置表头的对齐方式为居中
const tableData = ref([]);

const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);

  addProvinceNameLayer();
  getMapData();

  createPopUpLayer();

  setupSelectInteraction();
};

function getMapData() {
  getMapViewCase().then((res) => {
    // type;工程类别   0表示加固工程 1表示新建工程
    // category;工程类型 0表示大中小学校、1表示城镇住宅、2表示医院、3表示危险化学品厂、4表示电信网络、5表示电力网络、6表示农村居民、7表示重要交通生命线、8表示应急避难场所、9表示水库大坝、10表示其他
    pointsData.value = res.data;
    showPointsLayer();
  });
}

function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 2,
    style: function (feature) {
      const textstyle = new Style({
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#fff' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}

function setPopupData(list) {
  tableData.value.length = 0;
  for (let i = 0; i < list.length; i++) {
    let name = list[i].name;
    let type = Number(list[i].type) == 0 ? '加固工程' : '新建工程';
    let id = list[i].id;
    tableData.value.push({
      name: name,
      type: type,
      id: id,
    });
  }
}

function getSearchResult(list) {
  if (!list || list.length == 0) return;

  if (searchValue.value.type == 1 && searchValue.value.category == 1) {
    return list;
  }

  let result = [];

  list.forEach((item) => {
    let type = Number(item.type);
    let category = Number(item.category);

    //如果类型是全部
    if (searchValue.value.type == 1) {
      if (category + 2 == searchValue.value.category) {
        result.push(item);
      }
    }
    //如果类型是新建
    if (searchValue.value.type == 2) {
      if (type == 1) {
        if (1 == searchValue.value.category) {
          result.push(item);
        } else if (category + 2 == searchValue.value.category) {
          result.push(item);
        }
      }
    }
    //如果类型是加固
    if (searchValue.value.type == 3) {
      if (type == 0) {
        if (1 == searchValue.value.category) {
          result.push(item);
        } else if (category + 2 == searchValue.value.category) {
          result.push(item);
        }
      }
    }
  });

  return result;
}

function showPointsLayer() {
  if (!pointsData || !pointsData.value) return;
  if (pointsLayer && pointsLayer.value) {
    mapInstance.value.removeLayer(pointsLayer.value);
  }

  pointsLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 3,
  });

  mapInstance.value.addLayer(pointsLayer.value);

  for (let i = 0; i < pointsData.value.length; i++) {
    let item = pointsData.value[i];
    let pointList = getSearchResult(item.list);

    console.log('============', pointList);
    if (pointList && pointList.length > 0) {
      const lon = item.longitude;
      const lat = item.latitude;
      const point = new Feature({
        geometry: new Point([lon, lat]),
      });
      const style = new Style({
        image: new Icon({
          src: point_house_img,
          anchor: [0.5, 1],
          scale: 0.6,
        }),
      });
      point.set('type', 'point');
      point.set('pointIndex', i + '');
      point.setStyle(style);
      pointsLayer.value.getSource().addFeature(point);
    }
  }
}

const createPopUpLayer = () => {
  let popup = document.getElementById('map-popup');
  mapPopupLayer.value = new Overlay({
    element: popup,
    positioning: 'center-left',
    offset: [20, -25], // 偏移量，可根据需要进行调整
    autoPan: true,
  });
  mapInstance.value.addOverlay(mapPopupLayer.value);
};

const selectIconFeature = ref(null);
const setupSelectInteraction = () => {
  // 监听地图的点击事件
  mapInstance.value.on('click', (event) => {
    const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
    let pointsSource = pointsLayer.value.getSource();

    //点中了整个图标区域
    if (features.length > 0) {
      const tempFeature = features[0];
      if (tempFeature.get('type') == 'point') {
        //如果点中了大头针区域
        console.log('点击了大头针：');

        let index = Number(tempFeature.get('pointIndex'));
        let list = pointsData.value[index].list;
        let popupData = getSearchResult(list);
        console.log('================点击了大头针：', popupData);
        setPopupData(popupData);

        //如果前一个大头针处于放大状态，缩小大头针
        if (selectIconFeature.value) {
          selectIconFeature.value.getStyle().getImage().setScale(0.6);
        }
        selectIconFeature.value = tempFeature;
        const geometry = selectIconFeature.value.getGeometry();
        const coordinates = geometry.getCoordinates();

        //放大大头针
        selectIconFeature.value.getStyle().getImage().setScale(0.8);
        pointsSource.changed();
        popupElement.value.style.display = 'block';
        mapPopupLayer.value.setPosition(coordinates);
      } else if (tempFeature.get('type') == 'popup') {
        //如果点中弹框区域

        console.log('点击了弹框：');
        //这里跳转到工程概况页面
      }
    } else {
      //点中了大头针和弹框以外的区域，弹框消失，大头针缩小
      console.log('点击了地图：');
      if (selectIconFeature && selectIconFeature.value) {
        selectIconFeature.value.getStyle().getImage().setScale(0.6);
        pointsSource.changed();
        mapPopupLayer.value.setPosition(undefined);
      }
    }
  });
};

function hidePopup() {
  if (mapPopupLayer && mapPopupLayer.value) {
    selectIconFeature.value.getStyle().getImage().setScale(0.6);
    pointsLayer.value.getSource().changed();
    mapPopupLayer.value.setPosition(undefined);
  }
}

function gotoCaseInfo(row) {
  console.log('=========case id: ', row.id, row.name);
  router.push({ path: '/buildHouse/reinforceClassicCase/caseDetails', query: { id: row.id, name: row.name } });
}

function searchFn(val) {
  if (mapPopupLayer && mapPopupLayer.value) {
    selectIconFeature.value.getStyle().getImage().setScale(0.6);
    pointsLayer.value.getSource().changed();
    mapPopupLayer.value.setPosition(undefined);
  }

  searchValue.value = val;
  showPointsLayer();
}
</script>

<style scoped lang="scss">
.app-container {
  min-height: 1080px;
}
.app-main {
  display: flex;
  justify-content: space-between;
  .app-left {
    margin-left: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    /*height: calc(100% - 40px);*/
    width: 450px;
    &-total {
      width: 450px;
      height: 80px;
      background-size: 100% 100%;
      background-image: url('../../../assets/images/losses/title.png');
      font-size: 22px;
      color: #46ffff;
      line-height: 80px;
      padding-left: 120px;
      box-sizing: border-box;
      display: flex;
      position: absolute;
      top: 100px;
      span {
        font-family: DS-Digital;
        font-weight: 600;
        font-size: 36px;
        padding-top: 22px;
        display: flex;
        margin-left: 8px;
        i {
          display: block;
          width: 26px;
          height: 36px;
          background: #004c86;
          margin: 0 2px;
          font-style: normal;
          line-height: 36px;
          text-align: center;
        }
      }
    }

    &-item {
      width: 450px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
      &:nth-child(1) {
        height: 400px;
      }
      &:nth-child(2) {
        height: 240px;
      }
      &:nth-child(3) {
        height: 260px;
      }
    }
  }

  .app-map {
    width: 960px;
    height: 100%;
    //overflow: hidden; //test
    position: relative;
  }
  .app-right {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    /*height: calc(100% - 40px);*/
    width: 450px;

    &-item {
      width: 450px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
      &:nth-child(1) {
        height: 455px;
      }
      &:nth-child(2) {
        height: 455px;
      }
    }
  }
}
.popup-bg {
  width: 400px;
  height: 275px;
  /* background: linear-gradient(NaNdeg, rgba(5, 12, 53, 0.8) 0%, rgba(4, 16, 89, 0.8) 55%, rgba(6, 40, 150, 0.8) 100%); */
  background: rgba(6, 40, 150, 0.8);
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 2px solid #0190f9;
  display: flex;
  padding: 17px 15px;
  flex-direction: column;
  position: relative;
  .triangle {
    position: absolute;
    top: 50%;
    left: -10px;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #0190f9;
  }
  .popup-head {
    justify-content: center;

    display: flex;
    flex-direction: row;
    font-size: 18px;
    font-family: Source Han Sans CN-Bold, Source Han Sans CN;
    font-weight: bold;
    color: #ffffff;
    line-height: 23px;
    .popup-head-title {
      margin-left: auto;
    }
    .popup-head-x {
      margin-left: auto;
      width: 12px;
      height: 12px;
      color: #e6f4fd;
      opacity: 1;
    }
  }
  .popup-content {
    height: 100%;
    margin-top: 16px;
    display: flex;
    flex-direction: column;
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 500;
    color: #e6f4fd;
    line-height: 23px;
    .popup-content-title {
      background: #050426;
      border-radius: 0px 0px 0px 0px;
      opacity: 0.5;
      padding: 10px 34px;
      justify-content: space-between;
      display: flex;
      flex-direction: row;
    }
    .popup-table {
      width: 100%;
      height: 100%;
      margin-right: 20px;
      .centered-cell {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }
      .el-table {
        width: 90%;
        max-height: 150px;
        overflow-x: hidden;
        overflow-y: auto;
        z-index: 99;
        position: absolute;
        /* background: linear-gradient(135deg, #00032d 0%, #000c58 50%, #00032d 100%); */
        /* 背景透明 */
        background: rgba(0, 0, 0, 0);
        :deep(tr:hover > td) {
          background: rgba(71, 90, 219, 0.05) !important;
        }
        // top: 70px;
        // background-color: #00032D;
        /* background: linear-gradient(135deg, #00032d 0%, #000c58 50%, #00032d 100%); */
        :deep(.el-table__header) {
          background: rgba(5, 4, 38, 0.4);
          tr {
            background-color: transparent !important;
          }
          th.el-table__cell {
            background-color: transparent !important;
          }
          th.el-table__cell.is-leaf {
            border-bottom: none;
          }
        }

        :deep(.el-table__row) {
          background: rgba(5, 4, 38, 0.4);
        }
        :deep(.el-table__inner-wrapper)::before {
          display: none;
        }
      }
    }
  }
}
</style>
